import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { TimeConfigClass } from '../../../../common/common-config';
import { ConstructioninfoService } from '../constructioninfo.service';
import { StorageService } from '../../../../common/storage.service';

@Component({
  selector: 'app-info-constructioninfo-modifyrecord',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.css'],
  providers: [ConstructioninfoService],
})

export class InfoConstructioninfoModifyrecordComponent implements OnInit {

  businessId:any;  //商机id

  modifyRecordId: any;  //整改记录id
  timeConfig: any = new TimeConfigClass(); // 时间控件初始化
  modifyRecord: any = {}; //整改记录
  approves: any = {};  //审核结果
  operations: any = [];  //操作人记录
  operationsCol: any = [];  //操作人记录表头
  recordPhotoesImages: any = [];  //不合格图片
  reportPhotoesImages: any = [];  //提报照片
  approvePhotoesImages: any = [];  //审核不合格图片
  formObj: any = {};  //整改驳回
  errorFiel:any; //文件大小超标提示
  isShow: boolean = false; //弹框是否显示

  recordPhotoesError:any;

  recordPhotoes2Images: any = [];  //不合格图片
  recordPhotoesCode:string;  //不合格图片code

  recoverPhoto:any;// 恢复弹框图片
  recoverPhotoImages: any = [];// 恢复弹框图片

  recordPhotoes2Error: any;  //上传图片错误

  uploadRrl: string = 'zuul/com-dyrs-mtsp-fileservice/fileservice/fileDFSSave/api'; // 上传图片地址

  refuseDescriptionError: any;  //驳回说明错误提示

  isPunishShow: boolean = false; // 发起处罚弹出框
  punishmentsData: any = {}; // 传给处罚弹窗的数据

  modifyStatus: any;  //整改记录状态


  constructor(private router: Router, private constructioninfoService: ConstructioninfoService, private routeInfo: ActivatedRoute,
    public storage: StorageService) {
    //文件上传路径
    this.uploadRrl = (this.constructioninfoService.constructioninfoService.baseUrl || 'http://172.18.8.76/') + this.uploadRrl;
    //操作人信息表头
    this.operationsCol = [
      { field: 'sortNum', header: '序号', width: '100px',tem: true },
      { field: 'operationContent', header: '操作', width: '100px' },
      { field: 'afterSubmitStatus', header: '提交后状态', width: '100px',dic: 'modifystatus' },
      { field: 'creater', header: '提交人', width: '100px',dic: 'user_type' },
      { field: 'telephone', header: '手机号', width: '100px' },
      { field: 'submitTime', header: '提交时间', width: '100px' },
      { field: 'isAutoConfirmText', header: '是否是自动确认', width: '100px' },
    ];
  }


  ngOnInit() {
    // 获取路由id
    this.routeInfo.params.subscribe((params) => {
        this.modifyRecordId = params.id;
        this.businessId = params['infoId'];
    });
    this.initData();
  }


  /**
   * Description: 初始化数据
   * @Note:
   */
  initData(){
    this.storage.loading();
    this.constructioninfoService.modifyRecordDetail(this.modifyRecordId).then(
      data =>{
        if(data.result){
          this.storage.loadout();
          this.modifyRecord = data.data.modifyRecord;
          this.modifyStatus = this.modifyRecord.status;
          this.approves = data.data.approves;
          this.operations = data.data.operations;
          this.imgUrlData();
        }else{
          this.storage.loadout();
        }
      }
    );
  }


  /**
   * Description: 重置数据
   */
  resetData(){
    this.recordPhotoesImages = [];  //不合格图片
    this.reportPhotoesImages = [];  //提报照片
    this.approvePhotoesImages = [];  //审核不合格图片
  }


  /**
   * tabview能否进行切换
   */
  onChange(event) {
      event.open();
  }

  /**
   * 上传图片的回显
   */
  imgUrlData() {
    if(this.modifyRecord['photoesUrl']){
      for (let item of this.modifyRecord['photoesUrl'].split(',')) {
        this['recordPhotoesImages'] = [...this['recordPhotoesImages'], {
          source: item, thumbnail: item,
          width: '100px', maxWidth: '800px', title: ''
        }];
      }
    }
    if(this.modifyRecord['reportPhotoesUrl']){
      for (let item of this.modifyRecord['reportPhotoesUrl'].split(',')) {
        this['reportPhotoesImages'] = [...this['reportPhotoesImages'], {
          source: item, thumbnail: item,
          width: '100px', maxWidth: '800px', title: ''
        }];
      }
    }
    if(this.approves['photoesUrl']){
      for (let item of this.approves['photoesUrl'].split(',')) {
        this['approvePhotoesImages'] = [...this['approvePhotoesImages'], {
          source: item, thumbnail: item,
          width: '100px', maxWidth: '800px', title: ''
        }];
      }
    }

  }


  /**
   * Description: 图片大小超过指定值
   */
  onSelectError(event,id){
    this.errorFiel = event;
    let errorType:any = event[0].errorType;
    if(errorType == "typeError"){
      this[id.cancelLabel + 'Error'] = "上传的图片类型错误";
    }
    if(errorType == "maxError"){
      this[id.cancelLabel + 'Error'] = "图片大小超过限制";
    }
  }

  /**
   * 上传9张图片验证
   */
  onSelect9(event, id) {
    if(this.errorFiel && this.errorFiel.length!=0){
      id.clear();
      this.errorFiel = undefined;
      return
    }else{
      this.errorFiel = undefined;
    }
    if (event.files.length <= (20 - this[id.cancelLabel + 'Images'].length)) {
      event.upload();
      // this[id.cancelLabel + 'Error'] = '';
    } else {
      id.clear();
      this[id.cancelLabel + 'Error'] = '图片最多上传20张';
    }
  }

  /**
   * 上传你成功以后数据会显并更新对应图片的数据
   * @param event
   * @param f
   */
  onUpload(event, f) {
    // console.log(JSON.parse(event.xhr.responseText).result, JSON.parse(event.xhr.responseText).data);
    const result = JSON.parse(event.xhr.responseText);
    // console.log(f);
    if (result && result.result && result.data) {
      this.formObj[f.cancelLabel] = this.formObj[f.cancelLabel] ? this.formObj[f.cancelLabel] + ',' + result.data.fileCode :
        result.data.fileCode;
      for (let items of result.data.filePath.split(',')) {
        this[f.cancelLabel + 'Images'] = [...this[f.cancelLabel + 'Images'], {
          source: items, thumbnail: items,
          width: '100px', maxWidth: '800px', title: ''
        }];
      }
    }
  }

  /**
   * Description: 上传图片校验
   */
  changeImges() {
    if (!this.formObj['recordPhotoes2']) {
      this.recordPhotoes2Error = '请上传不合格照片';
    } else {
      this.recordPhotoes2Error = '';
    }
  }

  /**
   *删除图片并更新对应的图片数据
   * @param event
   * @param f
   */
  removeItem(event, f) {
    // console.log(f);
    let codeArray = this.formObj[f].split(',');
    codeArray.splice(event.index, 1);
    this.formObj[f] = codeArray.join(',');
    // console.log(f, this.foreman[f]);
    this[f + 'Images'] = this[f + 'Images'].filter((val, index) => index !== event.index);
  }

  /**
   * 刷新恢复弹框图片
   */
  recoverModifyImage() {
    this.formObj['recordPhotoes2'] = this.recoverPhoto;
    this.recordPhotoes2Images = this.recoverPhotoImages;
  }

  /**
   * Description: 整改驳回弹框
   * @Note:
   */
  openWindow(){
    this.constructioninfoService.getInfoStatus(this.businessId).then(
      data =>{
        if(data.result){
          if(data.data == 'constructionstatus_180108000006'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已中止，无法进行此操作！' });
            return false
          }else if(data.data == 'constructionstatus_180108000004'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已竣工，无法进行此操作！' });
            return false;
          } if(this.modifyStatus == 'modifystatus_180108000036'){
            this.storage.messageService.emit({ severity: 'error', detail: '此任务还未上传完成结果，无法进行此操作！' });
          }else{
            this.isShow = true;
            this.formObj['recordPhotoes2'] = "";
            this.formObj['refuseDescription'] = "";
            this.refuseDescriptionError = "";
            this.recordPhotoes2Error = "";
            let images = this.recordPhotoesImages
            if(this.reportPhotoesImages) {
              if(images) {
                images = images.concat(this.reportPhotoesImages);
              } else {
                images = this.reportPhotoesImages
              }
            }
            let imageCode = this.modifyRecord['photoes']
            if(this.modifyRecord['reportPhotoes']) {
              if(imageCode) {
                imageCode= imageCode.concat(",",this.modifyRecord['reportPhotoes']);
              } else {
                imageCode = this.modifyRecord['reportPhotoes']
              }
            }
            this.recordPhotoes2Images = images
            this.recordPhotoesCode = imageCode
            this.recoverPhoto = imageCode
            this.recoverPhotoImages = images
            this.formObj['recordPhotoes2'] = this.recordPhotoesCode;
          }
        }
      }
    );
  }

  /**
   * Description: 驳回整改
   * @Note:
   */
  modifyReject(){
    this.constructioninfoService.getInfoStatus(this.businessId).then(
      data =>{
        if(data.result){
          if(data.data == 'constructionstatus_180108000006'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已中止，无法进行此操作！' });
            return false;
          }else if(data.data == 'constructionstatus_180108000004'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已竣工，无法进行此操作！' });
            return false;
          }else{
            this.constructioninfoService.modifyRecordDetail(this.modifyRecordId).then(
              data =>{
                if(data.result){
                  this.storage.loadout();
                  this.modifyRecord = data.data.modifyRecord;
                  if(this.modifyRecord.status == 'modifystatus_180108000036'){
                    this.storage.messageService.emit({ severity: 'error', detail: '此任务还未上传完成结果，无法进行此操作！' });
                    return false;
                  }else{
                    this.formObj['id'] = this.modifyRecordId;
                    let flag: boolean = true;
                    if(!this.formObj.refuseDescription){
                      this.refuseDescriptionError = "请输入驳回说明";
                      flag =  false;
                    }
                    if(!this.formObj['recordPhotoes2']){
                      this.recordPhotoes2Error = "请上传不合格照片";
                      flag =  false;
                    }
                    if(!flag){
                      return false;
                    }
                    this.storage.loading();
                    this.isShow = false;
                    this.constructioninfoService.modifyReject(this.formObj).then(
                      data =>{
                        this.storage.loadout();
                        if(data.result){
                          this.recordPhotoesCode = "";
                          // this.approves = data.data;
                          this.resetData();
                          this.initData();
                        }else{
                        }
                      }
                    );
                  }
                }else{
                  this.storage.loadout();
                }
              }
            );
          }
        }
      }
    );
  }


  /**
   * Description: 处罚
   * @param
   */
  punishments(){
    this.constructioninfoService.getInfoStatus(this.businessId).then(
      data =>{
        if(data.result){
          if(data.data == 'constructionstatus_180108000006'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已中止，无法进行此操作！' });
            return false
          }else if(data.data == 'constructionstatus_180108000004'){
            this.storage.messageService.emit({ severity: 'error', detail: '该项目已竣工，无法进行此操作！' });
            return false;
          }else{
            this.punishmentsData.infoId = this.businessId;
            this.punishmentsData.triggerType = 'modifyId';
            this.punishmentsData.triggerId = this.modifyRecordId;
            this.isPunishShow = true;
          }
        }
      }
    );
  }

  /**
   * 修改发起处罚
   */
  changePunishShow(event) {
    this.isPunishShow = event;
  }

}
